import {
  inject, ref, Ref, App,
} from "vue";

type Option = {
  routes: any;
  history: any;
};

const ROUTERKEY = "__ROUTER__";
class Router {
  current: Ref<string>;

  routes: any;

  constructor(option: Option) {
    this.current = ref(option.history.url);
    this.routes = option.routes;

    option.history.bindEvents(() => {
      this.current.value = window.location.hash.slice(1);
    });
  }

  install(app: App) {
    app.provide(ROUTERKEY, this);
  }
}

export function createRouter(option: Option) {
  return new Router(option);
}

export function createWebHashHistory() {
  function bindEvents(fn: () => any) {
    window.addEventListener("hashchange", fn);
  }

  return {
    bindEvents,
    url: window.location.hash.slice(1) || "/",
  };
}

export function useRouter() {
  return inject(ROUTERKEY) as Router;
}
